//
//  NetWorkLoadingView.swift
//  Wanke
//
//  Created by BO ZHOU on 2020/10/26.
//

import UIKit

open class NetWorkLoadingView: UIView {
    
    /** 记录显示状态, 用来处理多个api调用的问题 */
    enum Status {
        case isShow
        case isHide
        case willHide
    }
    
    var status: Status = .isHide
    
    /** 记录loadingView的索引值, 每显示一次 +1, 每hide一次 -1, 如果为0则隐藏 */
    var indexTag: Int = 0
    
    lazy var imageBgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.init(hexString: "#FF363A43")
        view.cornerRadius = 10
        return view
    }()

    lazy var gifImageView: UIImageView = {
       
        let imageview = UIImageView()
        imageview.gifName = "加载中"
        
        return imageview
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        addSubview(imageBgView)
        addSubview(gifImageView)
    
//        KEY_WINDOW?.addSubview(self)
    }
    
//    willmo
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        let imagewh = 120 / SCREEN_WIDTH * 375
        imageBgView.frame = CGRect(x: self.width/2 - imagewh/2, y: self.height/2 - imagewh/2, width: imagewh, height: imagewh)
        
        let gitWH: CGFloat = 78
        gifImageView.frame = CGRect(x: self.width/2 - gitWH/2, y: self.height/2 - gitWH/2, width: gitWH, height: gitWH)
    }
    
    // MARK: 在keyWindow或者view上显示
    
    func showSelf() {
        
        indexTag += 1
        
        if self.status == .isHide {
            
            self.status = .isShow
            self.frame = self.superview?.bounds ?? KEY_WINDOW!.bounds
            
            self.superview?.bringSubviewToFront(self)
            
            animation {
                self.alpha = 1
            }
        } else if self.status == .willHide {
            self.status = .isShow
            NSObject.cancelPreviousPerformRequests(withTarget: self)
        }
    }
    
    private var actualHideBlock: (()->Void)?
    
    func hideSelf(actualHideBlock: (()->Void)? = nil) {
        indexTag -= 1
        
        self.actualHideBlock = actualHideBlock
        if indexTag == 0 {
            self.status = .willHide
            self.perform(#selector(_hideSelf), with: nil, afterDelay: 0.375)
        }
    }
    

    // 防止一个api调用成功之后, 调用另一个api, 导致loading闪两次
    @objc private func _hideSelf() {
        
        self.actualHideBlock?()
        self.status = .isHide
        animation {
            self.alpha = 0
        }
    }
        
    
//    deinit {
//        print("即将被释放...\(self)")
//
//        NetworkStatusManager.cacheNetView(view: self)
//    }
}
